{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From <ipython-input-5-64f94f245ddb>:60: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.\n",
      "Instructions for updating:\n",
      "Use `tf.global_variables_initializer` instead.\n",
      "Epoch:  0\n",
      "Accuracy:  0.9225\n",
      "done\n"
     ]
    }
   ],
   "source": [
    "''' gulli-macbookpro:m.01kk_s6 gulli$ tensorboard --logdir=run1:/tmp/mnist/ --port 6006   `'''\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "# reset everything to rerun in jupyter\n",
    "tf.reset_default_graph()\n",
    "\n",
    "# config\n",
    "batch_size = 100\n",
    "learning_rate = 0.5\n",
    "training_epochs = 5\n",
    "logs_path = \"/tmp/mnist/2\"\n",
    "\n",
    "# load mnist data set\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "mnist = input_data.read_data_sets('MNIST_data', one_hot=True)\n",
    "\n",
    "# input images\n",
    "with tf.name_scope('input'):\n",
    "    # None -> batch size can be any size, 784 -> flattened mnist image\n",
    "    x = tf.placeholder(tf.float32, shape=[None, 784], name=\"x-input\") \n",
    "    # target 10 output classes\n",
    "    y_ = tf.placeholder(tf.float32, shape=[None, 10], name=\"y-input\")\n",
    "\n",
    "# model parameters will change during training so we use tf.Variable\n",
    "with tf.name_scope(\"weights\"):\n",
    "    W = tf.Variable(tf.zeros([784, 10]))\n",
    "\n",
    "# bias\n",
    "with tf.name_scope(\"biases\"):\n",
    "    b = tf.Variable(tf.zeros([10]))\n",
    "\n",
    "# implement model\n",
    "with tf.name_scope(\"softmax\"):\n",
    "    # y is our prediction\n",
    "    y = tf.nn.softmax(tf.matmul(x,W) + b)\n",
    "\n",
    "# specify cost function\n",
    "with tf.name_scope('cross_entropy'):\n",
    "    # this is our cost\n",
    "    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n",
    "\n",
    "# specify optimizer\n",
    "with tf.name_scope('train'):\n",
    "    # optimizer is an \"operation\" which we can execute in a session\n",
    "    train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n",
    "\n",
    "with tf.name_scope('Accuracy'):\n",
    "    # Accuracy\n",
    "    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    \n",
    "# create a summary for our cost and accuracy\n",
    "tf.summary.scalar(\"cost\", cross_entropy)\n",
    "tf.summary.scalar(\"accuracy\", accuracy)\n",
    "\n",
    "# merge all summaries into a single \"operation\" which we can execute in a session \n",
    "summary_op = tf.summary.merge_all()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    # variables need to be initialized before we can use them\n",
    "    sess.run(tf.initialize_all_variables())\n",
    "\n",
    "    # create log writer object\n",
    "    writer = tf.summary.FileWriter(logs_path, graph=tf.get_default_graph())\n",
    "        \n",
    "    # perform training cycles\n",
    "    for epoch in range(training_epochs):\n",
    "        \n",
    "        # number of batches in one epoch\n",
    "        batch_count = int(mnist.train.num_examples/batch_size)\n",
    "        \n",
    "        for i in range(batch_count):\n",
    "            batch_x, batch_y = mnist.train.next_batch(batch_size)\n",
    "            \n",
    "            # perform the operations we defined earlier on batch\n",
    "            _, summary = sess.run([train_op, summary_op], feed_dict={x: batch_x, y_: batch_y})\n",
    "            \n",
    "            # write log\n",
    "            writer.add_summary(summary, epoch * batch_count + i)\n",
    "            \n",
    "        if epoch % 5 == 0: \n",
    "            print \"Epoch: \", epoch \n",
    "    print \"Accuracy: \", accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})\n",
    "    print \"done\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
